package com.sam.test;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

/**
 * @author Sam.Lee
 * @version Created：Apr 11, 2012 9:27:50 AM
 */
public class DDLConvertFieldTypeByCondition_Regex1 {

	private JTextArea textArea;
	private JFrame frame;

	public void addComponentsToPane(Container pane) {
		JButton button = new JButton("选择SQL文件并导出文件");
		pane.add(button, BorderLayout.NORTH);

		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				process();
			}
		});

		JScrollPane jScrollPane = new JScrollPane();
		textArea = new JTextArea();
		textArea.setLineWrap(true);
		textArea.setWrapStyleWord(true);
		jScrollPane.setViewportView(textArea);
		pane.add(jScrollPane, BorderLayout.CENTER);
	}

	private void createAndShowGUI() {
		frame = new JFrame("DB2表字段类型异同记录小工具");
		frame.setSize(700, 600);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		addComponentsToPane(frame.getContentPane());
		frame.setVisible(true);
	}

	private void process() {
		Pattern patternTableName = Pattern
				.compile("^(\\p{Blank}|\\t)*(CREATE|create)\\p{Blank}*(TABLE|table)\\p{Blank}*\"?\\p{Blank}*\\w+\\p{Blank}*\"?\\.\"?\\p{Blank}*\\w+\\p{Blank}*\"?");

		Pattern patternFieldName = Pattern
				.compile("^(\\p{Blank}|\\t)+\"?\\p{Blank}*\\w+\\p{Blank}*\"?");

		Pattern patternFieldType = Pattern
				.compile("(\\p{Blank}|\\t)+"
						+ "(((VARCHAR|varchar)\\p{Blank}*\\(\\p{Blank}*\\d+\\p{Blank}*\\))"
						+ "|((CHAR|char)\\p{Blank}*\\(\\p{Blank}*\\d+\\p{Blank}*\\))"
						+ "|((DOUBLE|double)(\\p{Blank}+|\\,|\\)))"
						+ "|((DATE|date)(\\p{Blank}+|\\,|\\)))"
						+ "|((TIME|time)(\\p{Blank}+|\\,|\\)))"
						+ "|((TIMESTAMP|timestamp)(\\p{Blank}+|\\,|\\)))"
						+ "|((INTEGER|integer)(\\p{Blank}+|\\,|\\)))"
						+ "|((SMALLINT|smallint)(\\p{Blank}+|\\,|\\)))"
						+ "|((CLOB|clob)\\p{Blank}*\\(\\p{Blank}*\\d+\\p{Blank}*\\))"
						+ "|((CLOB|clob)(\\p{Blank}+|\\,|\\)))"
						+ "|((BLOB|blob)\\p{Blank}*\\(\\p{Blank}*\\d+\\p{Blank}*\\))"
						+ "|((BLOB|blob)(\\p{Blank}+|\\,|\\)))"
						+ "|((DECIMAL|decimal)\\p{Blank}*\\(\\p{Blank}*\\d+\\p{Blank}*\\,\\p{Blank}*\\d+\\p{Blank}*\\)))"
						+ "|((DECIMAL|decimal)\\p{Blank}*\\(\\p{Blank}*\\d+\\p{Blank}*\\))"
						+ "|((LONG|long)\\p{Blank}+(VARCHAR|varchar)\\p{Blank}*)");
		File f1 = getSourceFile();
		File f2 = new File(f1.getParent() + "\\[analysisResult]" + f1.getName());
		String strLine = null;
		List<String> tableNameList = new ArrayList<String>();
		Map<String, Set<String>> recordEachFieldTypeMap = new TreeMap<String, Set<String>>();
		try {
			FileReader reader = new FileReader(f1);
			FileWriter writer = new FileWriter(f2);
			BufferedReader br = new BufferedReader(reader);
			BufferedWriter bw = new BufferedWriter(writer);

			while ((strLine = br.readLine()) != null) {
				String tableName = null;
				String fieldName = null;
				String fieldType = null;
				Matcher m1 = patternTableName.matcher(strLine);
				Matcher m2 = patternFieldName.matcher(strLine);
				Matcher m3 = patternFieldType.matcher(strLine);
				if (m1.find()) {
					tableName = m1.group().replace("\"", "").replace(" ", "")
							.trim();
					tableName = tableName.toUpperCase().replace("CREATE", "")
							.replace("TABLE", "").trim();
				}
				if (m2.find()) {
					fieldName = m2.group().replace("\"", "").trim().trim();
				}
				if (m3.find()) {
					fieldType = m3.group().replace(")", "").replace(" ", "")
							.trim();
					if (fieldType.endsWith(",")) {
						fieldType = fieldType.substring(0,
								fieldType.length() - 1);
					}
					if (fieldType.indexOf("(") != -1) {
						fieldType = fieldType + ")";
					}
				}
				if (tableName != null) {
					tableNameList.add(tableName);
				}
				if (fieldName != null && fieldType != null) {
					if (recordEachFieldTypeMap.get(fieldName) == null
							|| recordEachFieldTypeMap.get(fieldName).size() == 0) {
						recordEachFieldTypeMap.put(fieldName,
								new HashSet<String>());
					}
					Set<String> tableNameAndFieldTypeSet = recordEachFieldTypeMap
							.get(fieldName);

					List<String> typeList = new ArrayList<String>();
					for (String tableNameAndFieldType : tableNameAndFieldTypeSet) {
						String type = tableNameAndFieldType.split("@#@")[1];
						typeList.add(type);
					}
					if (!typeList.contains(fieldType)) {
						tableNameAndFieldTypeSet.add(tableNameList
								.get(tableNameList.size() - 1)
								+ "@#@"
								+ fieldType);
					}
				}
				System.out.println(strLine);
			}

			Iterator<Entry<String, Set<String>>> iter = recordEachFieldTypeMap
					.entrySet().iterator();
			while (iter.hasNext()) {
				Map.Entry<String, Set<String>> entry = (Map.Entry<String, Set<String>>) iter
						.next();
				if (entry.getValue().size() > 1) {
					// 写入文件
					bw.write("Field Name: " + "\"" + entry.getKey() + "\"");
					bw.newLine();
					bw.flush();
					for (String str : entry.getValue()) {
						bw.write("\t\tTable: " + str.split("@#@")[0]
								+ "\t\tType: " + str.split("@#@")[1]);
						bw.newLine();
						bw.flush();
					}

					// 写入TextArea
					textArea.append("Field Name: " + "\"" + entry.getKey()
							+ "\"\n");
					for (String str : entry.getValue()) {
						textArea.append("\t\tTable: " + "\""
								+ str.split("@#@")[0] + "\"\t\tType: "
								+ str.split("@#@")[1] + "\n");
					}
				}

			}
			br.close();
			bw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private File getSourceFile() {
		File file = null;
		JFileChooser jFileChooser = new JFileChooser();
		int tmp = jFileChooser.showSaveDialog(frame);
		if (tmp == JFileChooser.APPROVE_OPTION) {
			file = jFileChooser.getSelectedFile();
		}
		return file;
	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				new DDLConvertFieldTypeByCondition_Regex1().createAndShowGUI();
			}
		});
	}

}
